<template>
  <div style="display: flex; justify-content: space-around; gap: 24px">
    <a-input :modelValue="value" disabled="true" /><a-button
      type="primary"
      @click="open"
      >地图选点</a-button
    >
  </div>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    @ok="submit"
  >
    <span>详细地址：</span><a-input disabled="true" v-model:value="address" />
    <div id="container"></div>
  </BasicModal>
</template>
<script setup>
import { ref, unref, nextTick, onMounted } from 'vue';
import { BasicModal, useModalInner } from '@/components/Modal';
import AMapLoader from '@amap/amap-jsapi-loader';
const props = defineProps({
  value: {
    type: String,
  },
  title: {
    type: Object,
  },
  mapKey: {
    type: String,
    required: true,
  },
  width: {
    type: String,
    default: '50%',
  },
  height: {
    type: String,
    default: '70vh',
  },
  // 初始化的中心点
  center: {
    type: Array,
    default: [],
  },
  // 初始化的坐标
  poi: {
    type: Array,
  },
});
const [registerModal, { setModalProps, closeModal }] = useModalInner();

const emit = defineEmits(['submit', 'update:value']);
const mapInstance = ref();
const AMap = ref();
const marker = ref();
const address = ref('');
const pos = ref('');

// 触发父组件赋值
const setValue = () => {
  emit('update:value', address.value);
  emit('submit', { address: address.value, position: pos.value });
};

const initMap = () => {
  AMapLoader.load({
    key: props.mapKey,
    version: '2.0',
    plugins: ['AMap.Geocoder'],
  })
    .then((AMap) => {
      mapInstance.value = new AMap.Map('container', {
        zoom: 12,
        zooms: [2, 22],
        center: props.center,
      });
      mapInstance.value.on('click', (e) => {
        const { lat, lng } = e.lnglat;
        addMarker([lng, lat]);
      });

      const geocoder = new AMap.Geocoder();
      // 逆地址解析
      const getAddress = (lnglat) => {
        geocoder.getAddress(lnglat, function (status, result) {
          if (status === 'complete' && result.regeocode) {
            address.value = result.regeocode.formattedAddress;
          } else {
            address.value = '';
            log.error('根据经纬度查询地址失败');
          }
          setValue();
        });
      };
      // 添加坐标标记点
      const addMarker = (position) => {
        if (unref(marker)) {
          marker.value.remove();
        }
        pos.value = position;
        marker.value = new AMap.Marker({
          position,
          icon: new AMap.Icon({
            image:
              '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
            size: new AMap.Size(20, 28),
            imageSize: new AMap.Size(20, 28),
          }),
          offset: new AMap.Pixel(0, 0),
          anchor: 'bottom-center',
        });
        marker.value.setMap(mapInstance.value);
        getAddress(position);
      };

      if (props.poi) {
        addMarker(props.poi);
      }
    })
    .catch((e) => {
      console.log(e);
    });
};

const visible = ref(false);
const open = () => {
  visible.value = true;
  if (!mapInstance.value) {
    initMap();
  }
};

// 确定提交
const submit = () => {
  setValue();
  visible.value = false;
};

defineExpose({ open });
</script>
<style>
#container {
  height: 100%;
}
</style>
